package com.sise.wangzhan;

import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Classname MyAutoConfiguration
 * @Description TODO    在Spring容器中使用了@MyLoadBalanced修饰的RestTemplate实例，该实例会被加入配置类的RestTemplate集合中
 * @Date 2020/4/2 11:09
 * @Created by wangzhan
 */

@Configuration
public class MyAutoConfiguration {

    @Autowired(required = false)
    @MyLoadBalanced
    public List<RestTemplate> myTemplates = Collections.emptyList();

    @Bean
    public SmartInitializingSingleton myLoadBalancedRestTemplateInitializer(){
        System.out.println("========这个bean将在容器初始化时创建");

        return new SmartInitializingSingleton() {
            @Override
            public void afterSingletonsInstantiated() {
                for (RestTemplate tpl : myTemplates){
                    //创建一个自定义拦截器实例
                    MyInterceptor mi = new MyInterceptor();
                    //获取原来的拦截器
                    List list = new ArrayList(tpl.getInterceptors());
                    //将自定义拦截器添加
                    list.add(mi);
                    //将新的拦截器集合设置到RestTemplate实例
                    tpl.setInterceptors(list);
                }
            }
        };
    }

}
